package com.js.lib_common.mvp.presenter;


import com.js.lib_common.base.BasePresenter;
import com.js.lib_common.http.ApiCallback;
import com.js.lib_common.mvp.model.response.LoginResponse;
import com.js.lib_common.mvp.view.LoginView;
import com.js.lib_common.utils.FormDataUtil;
import com.js.lib_common.utils.MyMD5Util;

import java.util.HashMap;
import java.util.Map;

import okhttp3.RequestBody;

/**
 * Created by wz on 2019/5/17.
 */
public class LoginPresenter extends BasePresenter<LoginView> {
    public LoginPresenter(LoginView view) {
        attachView(view);
    }

    public void login(String name, String pwd) {
        mvpView.showLoading();
        Map<String, String> formMaildata = new HashMap<>();
        formMaildata.put("password", MyMD5Util.md5(pwd));
        formMaildata.put("username", name);
        formMaildata.put("grant_type", "password");
        Map<String, RequestBody> stringRequestBodyMap = FormDataUtil.generateRequestBody(formMaildata);

        addSubscription(apiStores.login(stringRequestBodyMap),
                new ApiCallback<LoginResponse>() {
                    @Override
                    public void onSuccess(LoginResponse response) {
                        if (response.getError()==null||response.getError().isEmpty()||response.getError().length()==0) {
//                            Gson gson = new Gson();
//                            String jsonStr = gson.toJson(response); //将对象转换成Json
//                            SPUtils.put(FlapDoorApplication.getAppContext(), "login", jsonStr);
//                            SPUtils.put(FlapDoorApplication.getAppContext(), "account", name);
//                            SPUtils.put(FlapDoorApplication.getAppContext(), "pwd", pwd);
                            mvpView.loginSuccess(response);
                        } else {
                            mvpView.loginFail(response.getError_description()+"");
                        }

                    }

                    @Override
                    public void onFailure(String msg) {
                        mvpView.loginFail(msg);
                    }


                    @Override
                    public void onFinish() {
                        mvpView.hideLoading();
                    }

                });
    }






}
